<template>
  <div class="main">
    <Header :showCarBtn="true">
      <BackHome />
      <div class="divider"></div>
      <a-select
        v-model:value="area.id"
        size="small"
        style="width: 6.875rem"
        :options="area.data"
        @change="onAreaChange">
        <template #suffixIcon>
          <svg t="1659511408750" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2332" width="12" height="12"><path d="M511.999488 819.413462 72.8374 204.586538 951.1626 204.586538Z" p-id="2333" fill="#ffffffd9"></path></svg>
        </template>
      </a-select>
      <a-select
        v-model:value="crossing.id"
        size="small"
        style="width: 6.25rem; marginLeft: 0.375rem"
        :options="crossing.data"
        @change="onCrossingChange">
        <template #suffixIcon>
          <svg t="1659511408750" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2332" width="12" height="12"><path d="M511.999488 819.413462 72.8374 204.586538 951.1626 204.586538Z" p-id="2333" fill="#ffffffd9"></path></svg>
        </template>
      </a-select>
    </Header>
    <Map ref="refMap"
      :area-id="area.id" 
      :center="mapConfig.center" 
      :geometry="mapConfig.geometry" 
      :start-time="mapConfig.startTime" 
      :end-time="mapConfig.endTime"/>
    <TimeQueryTool @time-query="timeQuery" ref="refTimeRange" class="time" />
    <div class="left container_vert">
      <Box class="left_1" title="路口综合指标">
        <CongestionState :value="congestionStats.value"/>
      </Box>
      <Box class="left_2" title="交通流量监测">
        <LineChart :x-axis="trafficVolumeStats.xAxis" :data="trafficVolumeStats.data" :color-array="trafficVolumeStats.colorArray"></LineChart>
      </Box>
      <Box class="left_3" title="排队长度及绿灯通行量检测">
        <BarChart :data="queueLengthStats.data" :color-array="queueLengthStats.colorArray"></BarChart>
      </Box>
    </div>
    <div class="middle container_hori_divide3">
      <Box :show-header="false">
        <Tip :tip-data="overviewStats[0]"></Tip>
      </Box>
      <Box :show-header="false">
        <Tip :tip-data="overviewStats[1]"></Tip>
      </Box>
      <Box :show-header="false">
        <Tip :tip-data="overviewStats[2]"></Tip>
      </Box>
    </div>
    <div class="right container_vert_divide3">
      <Box title="异常告警">
        <span class="warn_total">当前告警：<span style="color:#3EC92E;">{{warningStats.total +'条'}}</span></span>
        <ListInfo :data="warningStats.data"></ListInfo>
      </Box>
      <Box title="平均等待时间">
        <LineChart :x-axis="timeStats.xAxis" :data="timeStats.data"></LineChart>
      </Box>
      <Box title="平均停车次数">
        <BarChart :data="stopStats.data" :color-array="stopStats.colorArray"></BarChart>
      </Box>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref, reactive } from 'vue';
import Box from '@/components/Box.vue';
import LineChart from '@/components/LineChart.vue';
import BarChart from '@/components/BarChart.vue';
import Map from './body/Map.vue';
import BackHome from './body/BackHome.vue';
import Header from './header/Header.vue';
import ListInfo from './body/ListInfo.vue';
import Tip from './body/Tip.vue';
import CongestionState from './body/CongestionState.vue';
import SaturationPng from '@/assets/images/saturation.png';
import FlowPng from '@/assets/images/flow.png';
import BalancePng from '@/assets/images/balance.png';
import { useRoute, useRouter } from 'vue-router';
import TimeQueryTool from './body/TimeQueryTool.vue';
import { congestion, trafficVolume, queueLength, warning, time, stop, overview, getCrossingList } from '@/api/crossing';
import { useStore } from 'vuex';
import { areaList } from '@/api/area';
import moment from 'moment';
const store = useStore();
const route = useRoute();
const router = useRouter();
const refMap = ref(null);
const refTimeRange = ref(null);
const {id, crossingId} = route.query;

const area = reactive({
  id: id?parseInt(id):1,
  data: []
});

const crossing = reactive({
  id: crossingId,
  data: []
});
const { startTime, endTime } = getDefaultTimeRange();
const mapConfig = reactive({
  center: undefined,
  geometry: undefined,
  startTime,
  endTime
});

// 干线拥堵指数
const congestionStats = reactive({
  value: undefined
});
// 交通流量监测
const trafficVolumeStats = reactive({
  xAxis: [],
  data: [],
  colorArray: ['rgba(17, 155, 254, 0.25)', 'rgba(12, 77, 126, 0.25)', 'rgba(9, 35, 57, 0.25)']
});
// 排队长度监测
const queueLengthStats = reactive({
  data: [],
  colorArray: undefined
});
// 异常告警
const warningStats = reactive({
  total: 0,
  data: []
});
// 平均等待时间
const timeStats = reactive({
  xAxis: [],
  data: []
});
// 平均停车次数
const stopStats = reactive({
  data: [],
  colorArray: undefined
});
// 概览
const overviewStats = ref([
  {
    src: FlowPng,
    name: '交通流量',
    value: ''
  },
  {
    src: SaturationPng,
    name: '饱和度',
    value: ''
  },
  {
    src: BalancePng,
    name: '均衡度',
    value: ''
  }
]);
/** 干线拥堵指数 */
const getCongestion = (data) => {
  congestion(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      congestionStats.value = data.congestionValue;
    }
  });
};

/** 交通流量监测 */
const getTrafficVolume = (data) => {
  trafficVolume(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      trafficVolumeStats.xAxis = data.map(({ timePoint }) => timePoint);
      trafficVolumeStats.data = data.map(({ value }) => value);
    }
  });
};

/** 平均车辆密度 */
const getQueueLength = (data) => {
  queueLength(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      queueLengthStats.data = data.map(({ timePoint, value }) => {
        return { name: timePoint, value };
      });
    }
  });
};

/** 异常告警 */
const getWarning = (data) => {
  warning(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      warningStats.data = data.alarm.map(({ detail }) => detail);
      warningStats.total = data.total;
    }
  });
};

/** 平均通行时间 */
const getTime = (data) => {
  time(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      timeStats.xAxis = data.map(({ timePoint }) => timePoint);
      timeStats.data = data.map(({ value }) => value);
    }
  });
};

/** 交通事故 */
const getStop = (data) => {
  stop(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      stopStats.data = data.map(({ timePoint, value }) => {
        return { name: timePoint, value };
      });
    }
  });
};

/** 交通流量、饱和度、均衡度信息 */
const getOverview = (data) => {
  overview(data).then(({ retCode, data }) => {
    if (retCode === '0000_0') {
      overviewStats.value[0].value = data.flow +'辆';
      overviewStats.value[1].value = data.saturation+'%';
      overviewStats.value[2].value = data.balance+'%';
    }
  });
};

/** 请求页面数据 */
const getPageData = () => {
  const {startTime, endTime} = mapConfig;
  const date = moment(endTime).format('YYYY-MM-DD');
  const areaCode = area.id + '';
  const crossingId = crossing.id;
  const data1 = {areaCode, crossing:crossingId, startTime, endTime};
  const data2 = {areaCode, crossing:crossingId, date};
  getCongestion(data1);
  getQueueLength(data2);
  getTrafficVolume(data2);
  getWarning(data2);
  getTime(data2);
  getStop(data2);
  getOverview(data1);
};

/**下拉框选中干线变化 */
const onCrossingChange = () => {
  window.location.hash = '#/Crossing?id=' + area.id + '&crossingId=' + crossing.id;
  getPageData();
  const crossingIndex = crossing.data.findIndex(
    (item) => item.value === crossing.id
  );
  if (crossingIndex !== -1) {
    const geometry = crossing.data[crossingIndex].geometry[0];
    mapConfig.geometry = geometry;
  }
};

/** 更新路口显示数据 */
const updateCrossingData = async () => {
  const index = area.data.findIndex(
    (item) => item.value === area.id
  );
  if (index === -1) return;
  const areaInfo = area.data[index];
  const cIndex = areaInfo.serviceList.findIndex((item) => item.geometryType === 'intersection'&&item.type==='wfs');
  if (cIndex === -1) return;

  const url = areaInfo.serviceList[cIndex].url;
  await getCrossingList(url).then((res) => {
    crossing.data = res.features.map((item) => {
      return {
        value: item.properties.fid+'',
        label: item.properties.name?item.properties.name:'路口'+ item.properties.fid,
        geometry: item.geometry.coordinates[0]
      };
    });
    if(crossing.id == undefined) crossing.id = crossing.data[0].value;
    window.location.hash = '#/Crossing?id=' + area.id + '&crossingId=' + crossing.id;
    onCrossingChange();
  });
};

/** 示范区改变 */
const onAreaChange = (v) => {
  router.push({
    path: '/Area',
    query: {
      id: v
    }
  });
};

/** 请求示范区列表 */
async function getAreaList () {
  let _areaList = store.getters['map/areaList'];
  if (_areaList.length > 0) {
    area.data = _areaList.map(({ id, name, viewpoint, serviceList }) => { return { label: name, value: id, viewpoint, serviceList }; });
  } else {
    const { resCode, data } = await areaList();
    if (resCode === '00000') {
      area.data = data.map(({ id, name, viewpoint, serviceList }) => { return { label: name, value: id, viewpoint, serviceList }; });
      store.commit('map/cacheAreaList', data);
    }
  }
  const [crrentArea] = area.data.filter(({ value }) => value === area.id);
  mapConfig.center = JSON.parse(crrentArea.viewpoint);
  nextTick(() => {
    const mvtServices = crrentArea.serviceList.filter(item => item.type === 'mvt');
    refMap.value.addMvtLayer(mvtServices);
  });
  updateCrossingData();
}
/** 时间段搜索 */
const timeQuery = ({ startTime, endTime }) => {
  mapConfig.startTime = moment(startTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
  mapConfig.endTime = moment(endTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
  getPageData();
  refMap.value.onQueryTimeChange();
};

/**获取请求默认时间范围 */
function getDefaultTimeRange() {
  const yesterdayCurrentTime = new Date(Date.now() - 24*60*60*1000);
  let minute = yesterdayCurrentTime.getMinutes();
  minute = minute - minute % 5;
  minute = minute > 9 ? minute : ('0' + minute);
  const tStr = moment(yesterdayCurrentTime).format('YYYY-MM-DD HH:') + minute + ':00';
  const endTime = moment(tStr, 'YYYY-MM-DD HH:mm:ss').valueOf();
  const startTime = endTime - 5*60*1000;
  return {startTime, endTime};
}
getAreaList();
</script>

<style lang="less" scoped>
.left,
.right {
  width: 28.5%;
  height: calc(100% - var(--headerHeight) - var(--vMargin));
  bottom: var(--vMargin);
}
.left {
  left: var(--hMargin);
}
.right {
  right: var(--hMargin);
}

.middle {
  width: calc(
    43% - var(--hMargin) - var(--hMargin) - var(--hMargin) - var(--hMargin)
  );
  height: 13%;
  left: calc(28.5% + var(--hMargin) + var(--hMargin));
  bottom: var(--vMargin);
}

.left_1 {
  height: calc((100% - var(--vMargin)- var(--vMargin)) * 0.24);
}
.left_2 {
  height: calc((100% - var(--vMargin)- var(--vMargin)) * 0.36);
}
.left_3 {
  height: calc((100% - var(--vMargin)- var(--vMargin)) * 0.4);
}
.trend {
  width: 7.5rem;
  height: 7.5rem;
}
/deep/ .ant-select-selector {
  color: rgba(255, 255, 255, 0.85);
  background: rgba(9, 28, 46, 0.8) !important;
  border: solid 1px rgba(9, 28, 46, 1) !important;
  text-align: left;
}
.divider {
  width: 1px;
  height: 1.375rem;
  border-left: 1px solid #49a9d2;
  margin: 0 1rem;
}
.time {
  position: absolute;
  top: calc(var(--headerHeight) + var(--vMargin));
  left: calc(28.5% + var(--hMargin) + var(--hMargin));
}
.warn_total {
  position: absolute;
  right: 0.625rem;
  top: -2rem;
  font-size: 0.875rem;
}
</style>
